package app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @author AlexTien
 * @version currentVersion
 * @package app
 * @description
 * @createtime 17/7/7 下午12:00
 */
@RestController
public class Controller {
    @Autowired
    DiscoveryClient client;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    StringBuilder stringBuilder = new StringBuilder();

    @RequestMapping("/sentence")
    public String getSentence(){
        stringBuilder.delete(0,stringBuilder.length());
        stringBuilder.append(getWord("eureka-client-subject"));
        stringBuilder.append(" ");
        stringBuilder.append(getWord("eureka-client-VERB"));
        stringBuilder.append(" ");
        stringBuilder.append(getWord("eureka-client-article"));
        stringBuilder.append(" ");
        stringBuilder.append(getWord("eureka-client-adjective"));
        stringBuilder.append(" ");
        stringBuilder.append(getWord("eureka-client-noun"));
        stringBuilder.append(".");
        String result =  stringBuilder.toString();
        return result;
    }

    public String getWord(String service) {
        List<ServiceInstance> list = client.getInstances(service);
        if ( list != null && list.size() > 0) {
            URI uri = list.get(0).getUri();
            if(uri != null){
                return (new RestTemplate()).getForObject(uri,String.class);
            }
        }
        return null;
    }
    // 负载均衡得到word
    public String getWordLB(String service){
        ServiceInstance instance = loadBalancerClient.choose(service);
        return (new RestTemplate()).getForObject(instance.getUri(),String.class);
    }
}
